import logging

from pylons import request, response, session, tmpl_context as c
from pylons.controllers.util import abort, redirect_to

from cpswarehouse.lib.base import BaseController, render

log = logging.getLogger(__name__)

from cpswarehouse.lib.starquery import CpsStarQuery as StarQuery
from sqlalchemy import func

from cpswarehouse.model import YearDimension
from cpswarehouse.model.meta import Session

from cpswarehouse.lib.charts import RacePieChart

from pylons.decorators.cache import beaker_cache

class YearsController(BaseController):

    @beaker_cache()
    def index(self):

        starquery = StarQuery()
        years = starquery.select_race(func=func.sum).\
            select_year().\
            select_school().\
            group_by_year().\
            fetch_all()

        c.years = list(years)

        return render('/years/index.mako')


    @beaker_cache()
    def detail(self, year):

        starquery = StarQuery()
        years = starquery.select_race(func=func.sum).\
            select_year().\
            select_school().\
            where_year_is(year).\
            group_by_year().\
            fetch_all()

        c.year = Session.query(YearDimension).filter(YearDimension.year == year).one()

        years = list(years)
        race = years[0]

        pie_chart = RacePieChart(asian = race.asian,
                                 black = race.black,
                                 hispanic = race.hispanic,
                                 nativeamerican = race.nativeamerican,
                                 white = race.white)
        c.pie_chart = pie_chart
        
        c.years = list(years)

        return render('/years/detail.mako')
